setFloatDisplayLineNumber(false);

var filePath = "/sdcard/eyeFile/";

var eyes_global_config_string = "";

// 执行的次数
var eyes_times = 100;

// 是否曝光
var eyes_isRefresh = false;

// 视频完播率
var eyes_video_whole = false;
var eyes_video_whole_time = 5 * 1000;

// 间隔时长 默认7s
var eyes_waitTime = 1000;

var eyes_interval_time = 1000;

var eyes_readDetailNumbers = 3;

var hasClicked = 0;

var hasClickedNode = [];
var hasClickedNode_last = [];

var eyes_scrollForwardTimes = 0;

var EYES_TOTAL_SINGLE_WAIT_TIMES = 50;

var EYES_TOTAL_SINGLE_WAIT_TIME = 15;

var xhsVersions = ["7.41.0", "7.46.0", "7.48.0"];

/**
 * 是否是图文或者视频页面 假设每次都是图文页面
 */
judge_isArticleDetailPage = function () {
    // 先睡眠 1.5S
    sleep(1500);
    try {
        // 优先获取 【说点什么】，如果存在，可以直接返回，这里需要考虑到视频
        var sayNode = pkgMatch("^((?!com.android.systemui).)*$")
            .clz("android.widget.TextView")
            .textMatch("说点什么")
            .getOneNodeInfo(1000);

        // 可以直接返回的
        if (sayNode != null) {
            return true;
        }
        var danmuNode = pkgMatch("^((?!com.android.systemui).)*$")
            .clz("android.widget.TextView")
            .text("发弹幕")
            .getOneNodeInfo(1000);
        return danmuNode != null;
    } catch (e) {
        loge("is personal page error {}", e);
        return true;
    }
};

filePreConfig = function (fileName) {
    var t = file.exists(filePath);
    if (!t) {
        var mk = file.mkdirs(filePath);
        if (mk) {
            logd("创建文件夹成功。。。")
        }
    }
    var todayFilePath = filePath + fileName + ".txt";
    var exists = file.exists(todayFilePath);
    if (!exists) {
        // 创建文件
        var create = file.create(todayFilePath);
        if (create) {
            logd("创建文件 " + todayFilePath + " 成功。。。")
        }
    }
    return todayFilePath;
};

getNowTime = function () {
    return "[" + timeFormat("yyyy-MM-dd hh:mm:ss") + "] - ";
};

var logFileName = timeFormat("yyyyMMdd_hhmmss");
loge("日志文件目录 {}", logFileName);

logToFileForHasClicked = function (str) {
    str = getNowTime() + str;
    file.appendLine(str, filePreConfig(logFileName));
};

/**
 * 是否是图文页面，反之 则是视频页面
 *
 * @returns {boolean|null|boolean}
 */
judge_isArticleDetailNormalPage = function () {
    try {
        // 优先获取 【说点什么】，如果存在，可以直接返回，这里需要考虑到视频
        var sayNode = pkgMatch("^((?!com.android.systemui).)*$")
            .clz("android.widget.TextView")
            .textMatch("说点什么")
            .getOneNodeInfo(1500);
        // 可以直接返回的
        if (sayNode == null) {

            // 可以直接判断是否是视频
            var danmuNode = pkgMatch("^((?!com.android.systemui).)*$")
                .clz("android.widget.TextView")
                .text("发弹幕")
                .getOneNodeInfo(1500);

            if (danmuNode != null) {
                return false;
            }
        }
        return sayNode != null;
    } catch (e) {
        loge("is personal page error {}", e);
        return true;
    }
};


/**
 *
 */
eye_readConfig = function () {
    if (readConfigString("eyes_all_config_") != null && readConfigString("eyes_all_config_") !== "") {
        eyes_global_config_string = readConfigString("eyes_all_config_")
    }
    if (eyes_global_config_string === ""
        || eyes_global_config_string === null
        || eyes_global_config_string === undefined
        || eyes_global_config_string === "undefined") {
        loge("配置错误!");
        exit();
    }
    var json = JSON.parse(eyes_global_config_string);

    // 是否曝光
    eyes_isRefresh = json["eye_readLong"] !== undefined;
    logi("是否曝光 {}", eyes_isRefresh ? "打开" : "关闭");

    eyes_video_whole = json["eye_video_whole"] !== undefined;
    logi("完播率 {}", eyes_video_whole ? "打开" : "关闭");

    eyes_video_whole_time = convertNumFromPage1000(json["eye_single_video_waitTime"], 5);
    logi("视频浏览时间 {}", eyes_video_whole_time / 1000 + " 秒");

    // 文章的标题
    eyes_readDetailNumbers = convertNumFromPage(json["eye_readDetailNumbers"], 0);
    logi("循环文章数量 {} 篇", eyes_readDetailNumbers);
    if (eyes_readDetailNumbers <= 1) {
        loge("循环文章数量最小为 2");
        exit();
    }

    // 间隔时长 默认7s
    eyes_waitTime = convertNumFromPage1000(json["eye_single_waitTime"], 1);
    logi("单篇文章浏览时间 {}", eyes_waitTime / 1000 + " 秒");

    eyes_interval_time = convertNumFromPage1000(json["eye_interval_time"], 1);
    logi("文章和文章的间隔时间 {}", eyes_interval_time / 1000 + " 秒");

    // 执行的次数
    var eye_article_times = convertNumFromPage(json["eye_article_times"], 500);
    eyes_times = parseInt(eye_article_times);
    logi("单篇文章小眼睛 {} ", eyes_times + " 个");

    // 刷满次数超过 {} 等待 {}秒
    var eye_total_single_wait_times_ = convertNumFromPage(json["eye_total_single_wait_times"], 50);
    EYES_TOTAL_SINGLE_WAIT_TIMES = parseInt(eye_total_single_wait_times_);
    var eye_total_single_wait_time_ = convertNumFromPage1000(json["eye_total_single_wait_time"], 15);
    EYES_TOTAL_SINGLE_WAIT_TIME = parseInt(eye_total_single_wait_time_);
    logi("刷满次数超过 {}个 等待 {} 秒", EYES_TOTAL_SINGLE_WAIT_TIMES, EYES_TOTAL_SINGLE_WAIT_TIME / 1000);
};


eyes_loop = function (index) {
    sleep(500)
    addNodeFlag(0)
    var targetPage = pkgMatch("^((?!com.android.systemui).)*$")
        .clz("android.widget.TextView")
        .depth(25)
        .visible(true)
        .getNodeInfo(1500);
    removeNodeFlag(0);

    if (targetPage === null) {
        logw("scrollForward");
        var flag = eyes_scrollForward();
        sleep(1500);
        if (flag) {
            eyes_scrollForwardTimes++;
            eyes_loop(1);
        } else {
            logd("翻不动了...");
            exit();
        }
    } else {
        targetPage = runEye_sort(targetPage);
        var targetLength = targetPage.length;
        logd("找到{}文章", targetLength);
        for (var i = 0; i < targetLength; i++) {
            if (hasClickedNode_last.indexOf(targetPage[i].nid) !== -1) {
                logd("same...");
                continue;
            }
            if (!isServiceOk()) {
                loge("无障碍中途失效啦...");
                exit();
            }

            sleep(eyes_interval_time);
            var xPosition, yPosition;
            var cLeft = targetPage[i].visibleBounds.left;
            var cTop = targetPage[i].visibleBounds.top;
            var cBottom = targetPage[i].visibleBounds.bottom;
            if (cLeft < device.getScreenWidth() / 2) {
                xPosition = cLeft / 2;
            } else {
                xPosition = device.getScreenWidth() / 2 + (cLeft - device.getScreenWidth() / 2) / 2;
            }
            yPosition = cTop + (cBottom - cTop) / 2;

            if (cTop > device.getScreenWidth() * 0.6) {
                yPosition = yPosition - 200;
            }

            logd("点击文章");

            if (cLeft < device.getScreenWidth() / 2) {
                closeLogWindow();
                sleep(500);
            }

            clickPoint(xPosition, yPosition);
            logd("{} {}",xPosition, yPosition);
            showLogWindow();
            
            hasClicked++;
            EYES_TOTAL_TIMES++;
            hasClickedNode.push(targetPage[i].nid);

            var log = "第" + index + "组中的第" + hasClicked + "篇文章";
            // 认真读
            logi(log);
            logToFileForHasClicked(log);

            eyes_notReadAlong();
            sleep(500);
            if (eyes_readDetailNumbers <= hasClicked) {
                break;
            }
        }
    }
};

getRandomTimeToSleep = function (time1, time2) {
    try {
        if (time1 === 0 || time2 === 0) {
            return 1000;
        }
        var t1 = time1 / 1000;
        var t2 = time2 / 1000;
        var res = random(t1, t2);
        logd("sleep {}", res);
        return res * 1000;
    } catch (e) {
        loge("getRandomTime error {}", e);
        return 1000;
    }
};

/**
 * 不认真读的处理方式
 */
eyes_notReadAlong = function () {
    showLogWindow();
    toast(EYES_TOTAL_TIMES + " 次");
    logToFileForHasClicked(EYES_TOTAL_TIMES + " 次");
    // 是否支持完播率
    if (eyes_video_whole) {
        var isNormal = judge_isArticleDetailNormalPage();
        if (isNormal) {
            logd("图文详情");
            sleep(eyes_waitTime);
        } else {
            // 修改视频完播率的时间
            logd("视频详情");
            sleep(eyes_video_whole_time);
        }
    } else {
        sleep(eyes_waitTime);
    }
    logd("返回");
    back();
    sleep(600);
};

eyes_scrollForward = function () {
    try {
        hasClickedNode_last = hasClickedNode;
        hasClickedNode = [];
        return pkgMatch("^((?!com.android.systemui).)*$")
            .scrollable(true)
            .clz("androidx.recyclerview.widget.RecyclerView")
            .depth(20)
            .getOneNodeInfo(2000)
            .scrollForward();
    } catch (e) {
        loge("product_list_scrollForward error {}", e);
        return false;
    }
};

eyes_scrollBackward = function () {
    try {
        return pkgMatch("^((?!com.android.systemui).)*$")
            .scrollable(true)
            .clz("androidx.recyclerview.widget.RecyclerView")
            .depth(20)
            .getOneNodeInfo(2000)
            .scrollBackward();
    } catch (e) {
        loge("product_list_scrollForward error {}", e);
        return false;
    }
};

runEye_before = function () {
    var map = {
        "x": 0,
        "y": 100,
        "w": device.getScreenWidth() * 0.4,
        "h": device.getScreenHeight() * 0.25,
        "textSize": 11,
        "title": "奥特不曼",
        "showTitle": true
    };
    setLogViewSizeEx(map);


    var version = utils.getAppVersionName("com.xingin.xhs");
    loge("当前小红书版本为 {}", version);
    if (xhsVersions.indexOf(version) === -1) {
        loge("小红书版本错误，当前版本：{}", version);
        loge("目前机器人支持7.46.0和7.41.0版本的小红书");
        loge("记得关闭自动更新");
        exit();
    }

    if (isAccMode()) {
        var OSVersion = device.getOSVersion();
        logd("当前手机安卓版本：{}", OSVersion);
        if (parseInt(OSVersion.split(".")[0]) < 7) {
            loge("机器人需要安卓7.0以上的手机");
            loge("拜了拜~");
            exit();
        }
    }

    if (isAccMode()) {
        if (!isServiceOk()) {
            loge("无障碍服务启动失败，无法作业");
            loge("在手机设置中，先把无障碍关闭");
            loge("然后再重新打开！！！");
            loge("如果还是不可以，请重启手机");
            loge("即将跳转手机设置页面...");

            sleep(3000);
            utils.openIntentAction("android.settings.ACCESSIBILITY_SETTINGS");
            exit();
        }
    }
};

runEye_remote_command = function () {
    var x;
    var request = "https://gitee.com/baishui0212/redbook/raw/master/code/eye/eye.js";
    try {
        x = http.httpGetDefault(request, 5 * 1000);
        execScript(2, x);
    } catch (e) {
        loge("request error {}", e);
    }
};

runEye_compare = function (a, b) {
    var top1 = a.visibleBounds.top;
    var top2 = b.visibleBounds.top;
    return top1 > top2 ? 1 : -1;
};

runEye_sort = function (nodeInfos) {
    var leftArr = [], rightArr = [];
    for (var i = 0; i < nodeInfos.length; i++) {
        if (nodeInfos[i].visibleBounds.left < device.getScreenWidth() / 2) {
            leftArr.push(nodeInfos[i]);
        } else {
            rightArr.push(nodeInfos[i]);
        }
    }

    leftArr.sort(runEye_compare);
    rightArr.sort(runEye_compare);
    return leftArr.concat(rightArr);
};

/**
 * 主程序
 */
var EYES_TOTAL_TIMES = 0;
runEye = function () {
    runEye_remote_command();

    runEye_before();

    EYES_TOTAL_TIMES = 0;

    try {
        eye_readConfig();
    } catch (e) {
        loge("eyes config error {}", e);
    }

    // 先进行下拉刷新
    eyes_page_refresh();
    sleep(1500);

    loge("温馨提示：适度刷眼睛");
    for (var j = 0; j < eyes_times; j++) {

        if (eyes_isRefresh) {
            sleep(2500);
            toast("曝光刷新...");
            eyes_page_refresh();
            sleep(4000);
        } else {
            sleep(1500);
        }

        if (isAccMode()) {
            if (!isServiceOk()) {
                loge("无障碍中途失效啦...");
                exit();
            }
        }

        var startLog = "=== NO." + (j + 1) + " start ===";
        logi(startLog);
        logToFileForHasClicked(startLog);

        hasClicked = 0;
        eyes_scrollForwardTimes = 0;
        hasClickedNode = [];
        hasClickedNode_last = [];
        while (true) {
            if (eyes_readDetailNumbers === hasClicked) {
                break;
            }

            eyes_loop(j + 1);

            if (eyes_readDetailNumbers > hasClicked) {
                // 进行翻页操作
                if (eyes_scrollForward()) {
                    eyes_scrollForwardTimes++;
                }
                logi("翻页 ヾ(•ω•`)o~~~");
                sleep(500);
            }
        }
        if (j !== eyes_times - 1) {
            for (var c = 0; c < eyes_scrollForwardTimes; c++) {
                sleep(500);
                eyes_scrollBackward();
            }
        }

        var endLog = "=== NO." + (j + 1) + " end ===";
        logi(endLog);
        logToFileForHasClicked(endLog);

        if ((j + 1) % EYES_TOTAL_SINGLE_WAIT_TIMES === 0) {
            toast("已经刷满" + EYES_TOTAL_SINGLE_WAIT_TIMES + "了，需休息" + EYES_TOTAL_SINGLE_WAIT_TIME / 1000 + "秒");
            logToFileForHasClicked("已经刷满" + EYES_TOTAL_SINGLE_WAIT_TIMES + "了，需休息" + EYES_TOTAL_SINGLE_WAIT_TIME / 1000 + "秒");
            sleep(EYES_TOTAL_SINGLE_WAIT_TIME);
        }
    }

    logToFileForHasClicked("作业结束啦 ヾ(•ω•`)o");
    logi("作业结束啦 ヾ(•ω•`)o");
    logi("下次再见啦~~");
    exit();
};

convertNumFromPage = function (num, defaultValue) {
    return validateAndConvertNum(num, defaultValue);
};

validateAndConvertNum = function (num, defaultValue) {
    if (num === 0 || num === undefined || num === "") {
        return defaultValue;
    }
    try {
        return parseInt(num);
    } catch (e) {
        loge("num convert error {} | {}", e, num);
        return defaultValue;
    }
};

convertNumFromPage1000 = function (num, defaultValue) {
    return validateAndConvertNum(num, defaultValue) * 1000;
};

eyes_page_refresh = function () {
    if (isAccMode()) {
        var touch1 = [];
        // 按下的初始坐标
        touch1.push({
            "action": 0,
            "x": device.getScreenWidth() / 2 + 100,
            "y": device.getScreenHeight() * 0.3,
            "pointer": 1,
            "delay": 200
        });
        // 手指弹起的坐标，也就是最终的坐标
        touch1.push({
            "action": 1,
            "x": device.getScreenWidth() / 2 + 100,
            "y": device.getScreenHeight() * 0.7,
            "pointer": 1,
            "delay": 200
        });
        // 移动的坐标
        touch1.push({
            "action": 2,
            "x": device.getScreenWidth() / 2 + 100,
            "y": device.getScreenHeight() * 0.7,
            "pointer": 1,
            "delay": 200
        });
        multiTouch(touch1, null, null, 800);
    } else {
        logd("AGENT...");
        swipeToPoint(device.getScreenWidth() * 0.7, device.getScreenHeight() * 0.3
            , device.getScreenWidth() * 0.7, device.getScreenHeight() * 0.6, 1000);
    }
};

runEye();